package com.zwx.linkList.leetcode_2;


/**
 * 删除链表的倒数第n个元素
 * 给定一个链表，删除链表的倒数第n个节点，并返回链表的头结点
 *
 * @author 文希
 * @create 2019-07-02 22:59
 */
public class RemoveNthFromEnd {

    private static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = head;
        ListNode post = head;
        for (int i = 0; i < n; i++) {
            post = post.next;
        }
        if (post == null) {
            return head.next;
        }
        while (post.next != null) {
            post = post.next;
            pre = pre.next;
        }
        pre.next = pre.next.next;
        return head;
    }

    public static void main(String[] args) {
        ListNode listNode5 = new ListNode(5,null);
        ListNode listNode4 = new ListNode(4,listNode5);
        ListNode listNode3 = new ListNode(3,listNode4);
        ListNode listNode2 = new ListNode(2,listNode3);
        ListNode listNode1 = new ListNode(1,listNode2);

        ListNode listNode = removeNthFromEnd(listNode1, 3);
        System.out.println("listNode.toString() = " + listNode.toString());


    }

   /**
     * 定义链表的对象模型
     */
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode() {

        }

       @Override
       public String toString() {
           return "ListNode{" +
                   "val=" + val +
                   ", next=" + next +
                   '}';
       }

       public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
